# -*- coding: utf-8 -*-
#coding=utf-8

import web
import config
import cgi
import os

from action.user.base import userAction
from errors import *
from uploadmgr import httpUploadedFile
from model.image import image
from model.category import category


class refererAction(userAction):
    def __init__(self, name = '上传文件'):
        userAction.__init__(self, name)


    def POST(self, name):
        cgi.maxlen = int(config.MAX_UPLOAD_FILE_SIZE) * 1024 * 1024 # 2MB
        try:
            i = web.input(file={})
        except ValueError:
            return self.error(msg = '文件最大尺寸不能超过2M!')

        if name == 'file':
            return self.saveFile()
        elif name == 'image':
            return self.saveImage()
        elif name == 'audio':
            return self.saveAudio()
        elif name == 'video':
            return self.saveVideo()
        else:
            return self.notFound()


    def recordImage(self, f):
        import base64
        from imaging import imaging
        inputs = web.input()
        try: 
            iw = int(inputs['image_width'])
            ih = int(inputs['image_height'])
        except Exception, e:
            iw = config.IMAGE_XRES
            ih = config.IMAGE_YRES

        im = imaging(f.target())

        tmpfile = f.target() + ".tmp"
        data = im.resize(iw, ih) 
        file(tmpfile, 'w').write(data)
        os.unlink(f.target())
        os.rename(tmpfile, f.target())

        try:
            tw = int(inputs['thumbnail_width'])
            th = int(inputs['thumbnail_height'])
        except Exception, e:
            tw = config.THUMBNAIL_XRES
            th = config.THUMBNAIL_YRES

        blob = im.resize(tw, th)

        data = {
            'uuid':         f.uuid(),
            'desc':         self.htmlunquote(self.desc),
            'album':        self.album,
            'status':       self.status,
            'ref':          self.ref,
            'thumbnail':    base64.b64encode(buffer(blob)),
            'owner':        self.userid,
        }

        return image().insert(data)

    def recordAudio(self, f):
        import id3
        metadata = id3.get_audio_metadata(f.target())

        data = {
            'uuid':         f.uuid(),
            'title':        metadata['title'],
            'artist':       metadata['artist'],
            'album':        self.album,
            'status':       self.status,
            'thumbnail':    self.thumbnail,
            'desc':         self.htmlunquote(self.desc),
            'owner':        self.userid,
        }

        return audio().insert(data)
            
       
    def saveFile(self):
        inputParams = web.input()
        if inputParams.has_key('file') and not inputParams['file']:
            return self.error(msg = '未指定文件')

        f = None

        try: 
            self.desc = inputParams['desc']
            self.album = int(inputParams['album'])
            self.status = int(inputParams['status'])
            self.owner = inputParams['owner']
            self.ref = inputParams['ref'] if inputParams.has_key('ref') else None

            f = httpUploadedFile(inputParams.file)
            if f.mimetype().startswith('image'):
                c = self.recordImage(f)
                self.privData['text'] = self.imageUrl(c.lastrowid)
            elif f.mimetype().startswith('audio'):
                c = self.recordAudio(f)
                self.privData['text'] = self.audioUrl(c.lastrowid)
            elif f.mimetype().startswith('video'):
                c = self.recordVideo(f)
                self.privData['text'] = self.videoUrl(c.lastrowid)
            else:
                return self.error(msg = '未知的文件类型')
        except Exception, e:
            if f and os.path.exists(f.target()):
                os.unlink(f.target())
            return self.error(msg = '保存对象失败: %s' % e)

        return self.display('copyText')

    def saveImage(self):
        inputParams = web.input()
        if inputParams.has_key('file') and not inputParams['file']:
            return self.error(msg = '未指定文件')

        f = None

        try:
            self.desc = inputParams['desc']
            self.ref = inputParams['ref'] 
            self.album = int(inputParams['album'])
            self.status = int(inputParams['status'])
            self.owner = inputParams['owner']

            f = httpUploadedFile(inputParams.file)
            if f.mimetype() != 'image/jpeg':
                os.unlink(f.target())
                return self.error(msg = '图片文件格式不支持', url=self.makeUrl('/user/image/list'))
            self.recordImage(f)
        except Exception, e:
            if f and os.path.exists(f.target()):
                os.unlink(f.target())
            return self.error(msg='保存图片失败: %s' % e, url=self.makeUrl('/user/image/list'))
            
        return self.success(msg='图片上传成功', url=self.makeUrl('/user/image/list'))

    def saveAudio(self):
        inputParams = web.input()
        if inputParams.has_key('file') and not inputParams['file']:
            return self.error(msg = '未指定文件')

        f = None

        try:
            self.desc = inputParams['desc']
            self.status = int(inputParams['status'])
            self.thumbnail = int(inputParams['thumbnail'])
            self.album = int(inputParams['album'])

            f = httpUploadedFile(inputParams.file)
            if f.mimetype() != 'audio/mp3':
                os.unlink(f.target())
                return self.error(msg = '音频文件格式不支持', url=self.makeUrl('/user/audio/list'))
            self.recordAudio(f)
        except Exception, e:
            if f and os.path.exists(f.target()):
                os.unlink(f.target())
            return self.error(msg='保存音频失败: %s' % e, url=self.makeUrl('/user/audio/list'))

        return self.success(msg='音频上传成功', url=self.makeUrl('/user/audio/list'))

    def saveVideo(self):
        inputParams = web.input()
        if inputParams.has_key('file') and not inputParams['file']:
            return self.error(msg = '未指定文件')

        f = None

        try:
            self.desc = inputParams['desc']
            self.album = int(inputParams['album'])
            self.status = int(inputParams['status'])

            f = httpUploadedFile(inputParams.file)
            if f.mimetype() != 'video/mp4':
                os.unlink(f.target())
                return self.error(msg = '视频文件格式不支持', url=self.makeUrl('/user/video/list'))
            self.recordVideo(f)
        except Exception, e:
            if f and os.path.exists(f.target()):
                os.unlink(f.target())
            return self.error(msg='保存视频失败: %s' % e, url=self.makeUrl('/user/video/list'))

        return self.success(msg='视频上传成功', url=self.makeUrl('/user/video/list'))

    def recordVideo(self, f):
        import id3
        metadata = id3.get_video_metadata(f.target())
        screenshot = id3.get_video_screenshot(f.target())

        from imaging import imaging
        import StringIO
        thumbnail = imaging(StringIO.StringIO(screenshot)).resize(config.THUMBNAIL_XRES, 
                                                                  config.THUMBNAIL_YRES)
        import base64
        data = {
            'uuid':         f.uuid(),
            'album':        self.album,
            'status':       self.status,
            'desc':         self.desc,
            'title':        metadata['title'],
            'width':        int(metadata['width']),
            'height':       int(metadata['height']),
            'duration':     int(metadata['duration']),
            'screenshot':   buffer(screenshot),
            'thumbnail':    base64.b64encode(buffer(thumbnail)),
            'owner':        self.userid,
        }

        return video().insert(data)
